package com.codingapi.file.local.server.service.impl;

import com.codingapi.file.local.server.config.LocalFileConfig;
import com.codingapi.file.local.server.model.FileServerModel;
import com.codingapi.file.local.server.model.ImageWH;
import com.codingapi.file.local.server.service.FileValidateService;
import com.codingapi.file.local.server.service.ImgService;
import com.codingapi.file.local.server.service.UploadService;
import com.codingapi.file.local.server.utils.FileServerUtils;
import com.codingapi.file.local.server.utils.UploadDemo;
import com.lorne.core.framework.exception.ParamException;
import com.lorne.core.framework.exception.ServiceException;
import com.lorne.core.framework.utils.KidUtils;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * create by lorne on 2017/12/27
 */
@Service
public class ImgServiceImpl implements ImgService {


    @Autowired
    private UploadService uploadService;

    @Autowired
    private LocalFileConfig localFileConfig;

    @Override
    public FileServerModel[] uploadImage(MultipartFile[] file, String cutSize) throws ServiceException {
        FileServerModel[] fileServerModels = new FileServerModel[file.length];
        for (int i = 0; i < file.length; i++) {
            if (file.length <= 0) {
                throw new ParamException("file is null.");
            }
            if (cutSize == null) {
                cutSize = localFileConfig.getDefaultCutSize();
            }
            FileServerModel fileServerModel = uploadService.uploadFile(file[i]);
            List<ImageWH> whs = FileServerUtils.loadCutSize(cutSize);
            try {
                //上传至七牛云
                String url = upload(fileServerModel.getPath(), "pic/" + fileServerModel.getImgName());
                if (!url.isEmpty()) {
                    fileServerModel.setQiniuUrl(url);
                    File uploadFile = new File(localFileConfig.getFileServerPath() + "/" + fileServerModel.getPath());
                    uploadCutImages(whs, uploadFile);
                    fileServerModels[i] = fileServerModel;
                }
            } catch (Exception e) {
                throw new ServiceException(e);
            }
        }
        return fileServerModels;
    }


    private void uploadCutImages(List<ImageWH> whs, File sourceFile) throws ServiceException {
        //上传裁剪的图片
        try {
            for (ImageWH wh : whs) {
                String fileName = sourceFile.getName();
                String baseName = FilenameUtils.getBaseName(fileName);
                String ext = FilenameUtils.getExtension(fileName);
                String newFileName = baseName + "_" + wh.getW() + "x" + wh.getH() + "." + ext;
                File imgFile = new File(sourceFile.getParent() + "/" + newFileName);
                Thumbnails.of(sourceFile).size(wh.getW(), wh.getH()).toFile(imgFile);
            }
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    @Override
    public boolean cutImage(String filePath, String cutSize) throws ServiceException {

        if (StringUtils.isEmpty(filePath)) {
            throw new ParamException("filePath is null");
        }

        List<ImageWH> whs = FileServerUtils.loadCutSize(cutSize);
        String serverPath = localFileConfig.getFileServerPath();
        File uploadFile = new File(serverPath + "/" + filePath);
        if (!uploadFile.exists()) {
            throw new ParamException("file not exist");
        }
        uploadCutImages(whs, uploadFile);
        return true;
    }

    //设置好账号的ACCESS_KEY和SECRET_KEY
    String ACCESS_KEY = "nIvA3p0qp1GxBxhBtzlPMjmOjKhwdLkilgOMyb9w";
    String SECRET_KEY = "-DQbTJj6EHE09KTrxORVp-zu29rnWFwPb5lupBG2";
    //要上传的空间
    String bucketname = "image";
    //上传到七牛后保存的文件名
    //    String key = "my-java.png";
    //上传文件的路径
    //    String FilePath = "/.../...";
    //密钥配置
    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

    ///////////////////////指定上传的Zone的信息//////////////////
    //第一种方式: 指定具体的要上传的zone
    //注：该具体指定的方式和以下自动识别的方式选择其一即可
    //要上传的空间(bucket)的存储区域为华东时
    // Zone z = Zone.zone0();
    //要上传的空间(bucket)的存储区域为华北时
    // Zone z = Zone.zone1();
    //要上传的空间(bucket)的存储区域为华南时
    // Zone z = Zone.zone2();

    //第二种方式: 自动识别要上传的空间(bucket)的存储区域是华东、华北、华南。
    Zone z = Zone.autoZone();
    Configuration c = new Configuration(z);

    //创建上传对象
    UploadManager uploadManager = new UploadManager(c);

    public static void main(String args[]) throws IOException {
        new UploadDemo().upload();
    }

    //简单上传，使用默认策略，只需要设置上传的空间名就可以了
    public String getUpToken() {
        return auth.uploadToken(bucketname);
    }


    /**
     * 上传至七牛云
     *
     * @param
     * @author 清粥小菜
     * @Time 2018/3/12 9:42
     */
    public String upload(String FilePath, String key) throws IOException {
        try {
            //调用put方法上传
            Response res = uploadManager.put("H:\\test\\files" + FilePath, key, getUpToken());
            //打印返回的信息
            if (res.statusCode == 200) {
                return "http://p57r2vuuh.bkt.clouddn.com/pic/" + key;
            }
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            System.out.println(r.toString());
            try {
                //响应的文本信息
                System.out.println(r.bodyString());
            } catch (QiniuException e1) {
                //ignore
            }
        }
        return "";
    }

}
